#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using PLACEHR.Web.Categories.SystemSetting.Forms;
using PLACEHR.Web.Utilities;

#endregion

namespace PLACEHR.Web.Categories.SystemSetting.Controls
{
    public partial class ContentControl : UserControl, IHostedApplication
    {
        public ContentControl()
        {
            InitializeComponent();
            InitializeData();
        }

        #region IHostedApplication

        public void InitializeApplication()
        {
        }

        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            objElements.Add(new HostedToolBarButton(LanLayer.GetTrans(20), LanLayer.GetTrans(20), new IconResourceHandle("Outlook.NewItem.gif"), "Retrieve"));
            objElements.Add(new HostedToolBarSeperator());
            objElements.Add(new HostedToolBarButton(LanLayer.GetTrans(21), LanLayer.GetTrans(21), new IconResourceHandle("CRM.ico_16_5006.gif"), "OpenSelected"));
            objElements.Add(new HostedToolBarSeperator());
            objElements.Add(new HostedToolBarButton(LanLayer.GetTrans(22), LanLayer.GetTrans(22), new IconResourceHandle("CRM.ico_16_1070.gif"), "Add"));
            //objElements.Add(new HostedToolBarSeperator());
            //objElements.Add(new HostedToolBarButton(LanLayer.GetTrans(23), LanLayer.GetTrans(23), new IconResourceHandle("CRM.ico_16_5010.gif"), "DeleteSelected"));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }

        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            string strAction = (string)objButton.Tag;
            switch (strAction)
            {
                case "Retrieve":
                    InitializeData();
                    break;
                case "OpenSelected":
                    OpenDetailForm();
                    break;
                case "Add":
                    AddDetailForm();
                    break;
                case "DeleteSelected":
                    if (lvwData.SelectedItems != null && lvwData.SelectedItems.Count > 0)
                    {
                        MessageBox.Show("Please make sure you want to delete selected Content!", "Prompt", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,
                                        (obj, arg) =>
                                        {
                                            if (((MessageBoxWindow)obj).DialogResult == DialogResult.Yes)
                                            {
                                                DeleteSelected();
                                                InitializeData();
                                            }
                                        });
                    }
                    else
                    {
                        MessageBox.Show("Please select which Content you want to delete!");
                    }
                    break;
            }
        }

        #endregion

        #region Method

        private void DeleteSelected()
        {
            foreach (ListViewItem lvwItem in lvwData.SelectedItems)
            {
                Content c = lvwItem.Tag as Content;
                var deleteContent = Global.Context.Contents.FirstOrDefault(p => p.ContentId == c.ContentId);

                List<ContentTranslation> deleteTransList = new List<ContentTranslation>();
                foreach (var trans in deleteContent.ContentTranslations)
                {
                    var currTrans = Global.Context.ContentTranslations.FirstOrDefault(p => p.ContentTranslationId == trans.ContentTranslationId);
                    deleteTransList.Add(currTrans);
                }

                foreach (var item in deleteTransList)
                {
                    Global.Context.ContentTranslations.DeleteObject(item);
                }

                Global.Context.Contents.DeleteObject(deleteContent);
                LanLayer.RefreshItem(deleteContent.ContentId);

                //DataRow item = lvwItem.Tag as DataRow;
                //SqlHelper.ExecuteNonQuery(Global.ConnectionString, CommandType.Text, string.Format("delete from [Catagory] where id = {0}", item["ID"].ToString()));
            }

            Global.Context.SaveChanges();
        }

        private void OpenDetailForm()
        {
            if (lvwData.SelectedItem != null)
            {
                Content item = lvwData.SelectedItem.Tag as Content;
                ContentForm form = new ContentForm();
                form.currItem = item;
                form.FormClosed += new Gizmox.WebGUI.Forms.Form.FormClosedEventHandler(form_FormClosed);
                form.ShowDialog();
            }
        }

        void form_FormClosed(object sender, FormClosedEventArgs e)
        {
            ContentForm form = sender as ContentForm;
            if (form.DialogResult == DialogResult.OK)
            {
                btnSearch_Click(sender, e);
            }
        }

        private void AddDetailForm()
        {
            ContentForm form = new ContentForm();
            form.defaultCategory = cbxCategory.SelectedValue.ToString();
            form.FormClosed += new Gizmox.WebGUI.Forms.Form.FormClosedEventHandler(form_FormClosed);
            form.ShowDialog();
        }

        private void InitializeData()
        {
            cbxCategory.DataSource = Utility.GetContentCategoryList();
            cbxCategory.DisplayMember = "value";
            cbxCategory.ValueMember = "key";

            List<Content> list = Global.Context.Contents.ToList();
            this.BindDataToListView(list);

            clhdContentID.Text = LanLayer.GetTrans(7);
            clhdCategory.Text = LanLayer.GetTrans(28);
            clhdDefaultValue.Text = LanLayer.GetTrans(29);
            clhdChinese.Text = LanLayer.GetTrans(30);
            clhdEnglish.Text = LanLayer.GetTrans(31);
            lblCategory.Text = LanLayer.GetTrans(28);
            btnSearch.Text = LanLayer.GetTrans(27);
        }

        private void BindDataToListView(List<Content> list)
        {
            try
            {
                lvwData.Items.Clear();
                lvwData.BeginUpdate();
                int No = 1;
                foreach (var item in list)
                {
                    ListViewItem lvwItem = new ListViewItem("");
                    lvwItem.SubItems.AddRange(new string[6]);

                    lvwItem.SubItems[0].Text = (No++).ToString();
                    lvwItem.SubItems[1].Text = item.ContentId.ToString();
                    lvwItem.SubItems[2].Text = item.CategoryCode;
                    lvwItem.SubItems[3].Text = item.DefaultValue;

                    var csTrans = item.ContentTranslations.FirstOrDefault(p => string.Equals(p.LanguageCode.Trim(), Constants.ZhCode, StringComparison.OrdinalIgnoreCase));
                    var enTrans = item.ContentTranslations.FirstOrDefault(p => string.Equals(p.LanguageCode.Trim(), Constants.EnCode, StringComparison.OrdinalIgnoreCase));
                    lvwItem.SubItems[4].Text = csTrans == null ? string.Empty : csTrans.Translation;
                    lvwItem.SubItems[5].Text = enTrans == null ? string.Empty : enTrans.Translation;
                    lvwItem.Tag = item;

                    lvwData.Items.Add(lvwItem);
                }
                lvwData.EndUpdate();
            }
            catch (Exception ex)
            { 
                
            }
        }

        #endregion

        #region Event

        private void lvwData_DoubleClick(object sender, EventArgs e)
        {
            OpenDetailForm();
        }

        #endregion

        private void btnSearch_Click(object sender, EventArgs e)
        {
            IEnumerable<Content> list = Global.Context.Contents.ToList();
            if (cbxCategory.SelectedValue != null && !string.IsNullOrWhiteSpace(cbxCategory.SelectedValue.ToString()))
            {
                list = list.Where(p => p.CategoryCode.Equals(cbxCategory.SelectedValue.ToString(), StringComparison.OrdinalIgnoreCase));
            }

            if (!string.IsNullOrWhiteSpace(tbxContent.Text))
            {
                list = list.Where(p => p.DefaultValue.Equals(tbxContent.Text.Trim(), StringComparison.OrdinalIgnoreCase)
                                     || (p.ContentTranslations != null && p.ContentTranslations.Any(t => t.Translation != null && t.Translation.ToLower().Contains(tbxContent.Text.ToLower().Trim()))));
            }

            this.BindDataToListView(list.ToList());
        }
    }
}